﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeChatParking.Entity.Enums;

namespace WeChatParking.Core.BLL
{
    public class ServerCode
    {
        /// <summary>
        /// 是否存在代码
        /// </summary>
        /// <param name="DeviceClient_code">客户端代码</param>
        /// <returns></returns>
        public bool ExistsClient_code(string DeviceClient_code)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                var precidate = new { DeviceClient_code = DeviceClient_code };
                return dbContext.Count<Entity.Device>(precidate, null) > 0;
            }
        }
        #region 进出场记录
        /// <summary>
        /// 进场数据添加  推送进场记录到智慧通行平台
        /// </summary>
        /// <param name="model"></param>
        /// <param name="imgFileName"></param>
        /// <returns></returns>
        public int ServerAddIn(Entity.Api.InOrOut model, string imgFileName)
        {
            try
            {
                Entity.CarRecord car = new Entity.CarRecord();
                car.carBrand = model.Car_plate;
                car.inTime = Util.Conv.ToDate(model.Time, DateTime.Now);
                car.Inimg = imgFileName;
                car.outTime = null;
                car.Outimg = null;
                car.create_time = DateTime.Now;
                car.update_time = DateTime.Now;
                car.create_user = "SERVER";
                car.update_user = "SERVER";
                car.status = 1;
                car.Guid = model.Guid;
                car.retain1 = model.Car_type.ToString();
                Core.BLL.Device debll = new Device();
                var device = debll.Get(model.Parking_code);
                car.Enterprise_ID = device.Enterprise_ID;
                car.retain2 = model.Parking_code;
                Core.BLL.Enterprise enbll = new Enterprise();
                var Tcente = enbll.Get(device.TcEnterprise_ID);
                car.Enterprise_Code = Tcente.Enterprise_Code;
                car.Enterprise_Name = Tcente.Enterprise_Name;

                using (var dbContext = Repository.DbContext.Create())
                {
                    int line = dbContext.Insert<Entity.CarRecord>(car);
                    string json = WeChatParking.Util.Conv.ToJson(car);
                    LogHelper.Info(json, Entity.Enums.LogType.Server_In);
                    //发送微信消息
                    SendNotifyMsg(car);
                    //进场记录通知银联
                    string request = "";
                    //使用智慧通行平台
                    if (WeChatParking.Core.Payment.WeixinPay.WxpayConfig.IsUnionPay)
                    {
                        var res1 = new Core.Payment.UnionPay.ActiveAct().noticeEntrance(line.ToString(), car.carBrand, car.inTime, Tcente.ID.ToString(), Tcente.Enterprise_Name, out request);
                        LogHelper.Info(res1, "无感主动推送进场记录请返回");
                        LogHelper.Info(request, Entity.Enums.LogType.UnionPay_In);
                        var res = new Core.Payment.UnionPay.ActiveAct().carStatusQuery(model.Car_plate, out  request);
                        LogHelper.Info(request, Entity.Enums.LogType.UnionPay_carStatus);
                        LogHelper.Info(res, "无感主动查询车辆状态请返回");
                        //{"resultCode":0,"description":"成功","data":{"signTime":"2018-09-06T07:22:52.000Z","status":0,"statusDescription":1}}

                        WeChatParking.Core.Payment.UnionPay.carQuery carQueryModel = (WeChatParking.Core.Payment.UnionPay.carQuery)Newtonsoft.Json.JsonConvert.DeserializeObject(res, typeof(WeChatParking.Core.Payment.UnionPay.carQuery));
                        if (carQueryModel.resultCode == "0")
                        {
                            if (carQueryModel.data.statusDescription != 4)
                            {
                                Entity.Car_Plate carModel = new Entity.Car_Plate();
                                carModel.Car_plate = car.carBrand;
                                carModel.signNo = "";
                                carModel.status = carQueryModel.data.status;
                                carModel.statusDescription = carQueryModel.data.statusDescription;
                                new WeChatParking.Core.BLL.Car_Plate().UnionPayCar_Plate(carModel);
                            }
                        }
                    }
                    return line;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "Server添加进场车辆记录");
                return 0;
            }
        }
        /// <summary>
        /// 出场记录修改  推送到出场记录智慧通行平台
        /// </summary>
        /// <param name="model"></param>
        /// <param name="imgFileName"></param>
        /// <returns></returns>
        public bool ServerAddOut(Entity.Api.InOrOut model, string imgFileName)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    //判断进出记录是否已在数据库中
                    var precidateGuid = new { Guid = model.Guid };
                    var isCar = dbContext.GetList<Entity.CarRecord>(precidateGuid, null).FirstOrDefault();
                    if (isCar != null)
                        return true;
                    Core.BLL.Device debll = new Device();
                    var device = debll.Get(model.Parking_code);

                    var precidate = new { status = 1, carBrand = model.Car_plate, Enterprise_ID = device.Enterprise_ID };
                    var car = dbContext.GetList<Entity.CarRecord>(precidate, null).FirstOrDefault();
                    if (car == null)
                        return false;
                    else
                    {

                        string json = WeChatParking.Util.Conv.ToJson(car);
                        LogHelper.Info(json, Entity.Enums.LogType.Server_Out);
                        var Tcente = new Enterprise().Get(device.TcEnterprise_ID);
                        string request = "";
                        //使用智慧通行平台
                        if (WeChatParking.Core.Payment.WeixinPay.WxpayConfig.IsUnionPay)
                        {
                            var res = new Core.Payment.UnionPay.ActiveAct().noticeExit(car.id.ToString(), car.carBrand, car.inTime, Tcente.ID.ToString(), Tcente.Enterprise_Name, out request);
                            LogHelper.Info(res, "无感主动推送出场记录请返回");
                            LogHelper.Info(request, Entity.Enums.LogType.UnionPay_Out);

                            //车辆状态是可无感代扣的状态、查询出是否之前无感支付过、并且订单还在支付中的状态，如果订单是在5分钟内的，直接发起退款
                            var car_plateModel = new WeChatParking.Core.BLL.Car_Plate().Get(String.Format("Car_plate='{0}'", model.Car_plate), "").FirstOrDefault();

                            if (car_plateModel.status == 0 && car_plateModel.statusDescription == 1)
                            {
                                var list = new WeChatParking.Core.BLL.Order_info().getOrderList(model.Car_plate);
                                if (list != null && list.Count > 0)
                                {
                                    foreach (var item in list)
                                    {
                                        Payment.UnionPay.retry retryModel = new Payment.UnionPay.retry()
                                       {
                                           order_id = item.order_id,
                                           upRefundId = "",
                                           status = 0,
                                           type = 4,
                                           time = DateTime.Now,
                                           num = 0
                                       };
                                        new BLL.retry().Add(retryModel);
                                    }
                                }
                                var order=new Core.BLL.Order_info().GetOrder(car.Guid);
                                if (order!=null)
                                {
                                    order.Guid=model.Guid;
                                    new Core.BLL.PrepaidOrder().Update(order);
                                }
                            }
                        }
                        car.outTime = Util.Conv.ToDate(model.Time, DateTime.Now);
                        car.Outimg = imgFileName;
                        car.update_time = DateTime.Now;
                        car.status = 2;
                        car.Guid = model.Guid;
                        return dbContext.Update(car);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "Server修改进场记录为出场");
                    return false;
                }
            }
        }
        #endregion
        /// <summary>
        /// 现场扫码缴费，找出进场记录，并修改retain3的值为XCPay
        /// 新增无感支付，客户端推送后，查询用户是否可以无感支付，
        /// 可以无感支付的话，直接进行无感支付流程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool XCPay(Entity.Api.XCPay model)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                decimal Fee = Convert.ToDecimal((model.Fee / 100).ToString() + "." + ((model.Fee % 100).ToString().Length > 1 ? (model.Fee % 100).ToString() : "0" + (model.Fee % 100).ToString()));
                Core.BLL.Device debll = new Device();
                var device = debll.Get(model.Parking_code);
                var precidate = new { status = 1, carBrand = model.Car_plate, Enterprise_ID = device.Enterprise_ID };
                var car = dbContext.GetList<Entity.CarRecord>(precidate, null).FirstOrDefault();
                if (car == null)
                    return false;

                //查询智慧通行平台是否可以无感支付
                if (WeChatParking.Core.Payment.WeixinPay.WxpayConfig.IsUnionPay)
                {
                    // var car_plateModel = new WeChatParking.Core.BLL.Car_Plate().GetModel(model.Car_plate);
                    var car_plateModel = new WeChatParking.Core.BLL.Car_Plate().Get(String.Format("Car_plate='{0}'", model.Car_plate), "").FirstOrDefault();
                    if (car_plateModel != null)
                    {
                        // LogHelper.Info("进入无感支付流程1");
                        if (car_plateModel.status == 0 && car_plateModel.statusDescription == 1)
                        {
                            var en = new Core.BLL.Enterprise().Get(device.TcEnterprise_ID);
                            // LogHelper.Info("进入无感支付流程2");
                            var order = new Core.BLL.PrepaidOrder().CreateOrder(car_plateModel.Wx_userId, car.id, Fee, "", 0, true);
                            if (order != null)
                            {

                                WeChatParking.Core.Payment.UnionPay.ActiveAct payBll = new Payment.UnionPay.ActiveAct();
                                string request = "";
                                var res = payBll.payBill(order.order_id, order.order_id, model.Car_plate, model.Fee, model.Fee, car.inTime, DateTime.Now, en.ID.ToString(), en.Enterprise_Name, en.accSplitData, out request);
                                Dictionary<String, String> rspDic = (Dictionary<String, String>)Newtonsoft.Json.JsonConvert.DeserializeObject(res, typeof(Dictionary<String, String>));
                                //LogHelper.Info(request, "无感主动支付请求付");
                                //LogHelper.Info(Newtonsoft.Json.JsonConvert.SerializeObject(res), "无感主动支付请返回");
                                if (rspDic.ContainsKey("resultCode"))
                                {
                                    int code = int.Parse(rspDic["resultCode"]);
                                    if (code == 0)
                                    {
                                        order.order_status = 2;
                                        new Core.BLL.PrepaidOrder().Update(order);

                                        Payment.UnionPay.retry retryModel = new Payment.UnionPay.retry()
                                        {
                                            order_id = order.order_id,
                                            upRefundId = "",
                                            status = 0,
                                            type = 0,
                                            time = DateTime.Now,
                                            num = 0
                                        };
                                        new BLL.retry().Add(retryModel);
                                    }
                                }
                            }
                        }
                    }
                }
                try
                {
                    car.update_time = DateTime.Now;
                    car.retain3 = "XCPay";
                    car.retain4 = Fee.ToString();
                    string json = WeChatParking.Util.Conv.ToJson(car);
                    LogHelper.Info(json, Entity.Enums.LogType.Server_XCPay);
                    dbContext.Update(car);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "Server现场缴费找出进场记录并修改预留字段3,4");
                    return false;
                }
                return true;

            }
        }
        #region 预支付
        /// <summary>
        /// 下发预支付
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="OrderFields"></param>
        /// <param name="isDesc"></param>
        /// <returns></returns>
        public Entity.Api.YPay GetYPay(string filter, string OrderFields = "", bool isDesc = false)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    string sql = "select * from YPay";
                    if (filter.Length > 0)
                        sql += "  where  " + filter;
                    if (OrderFields.Length > 0)
                    {
                        if (isDesc)
                            sql += "   ORDER BY  " + OrderFields + "  DESC";
                        else
                            sql += "   ORDER BY  " + OrderFields;
                    }
                    return dbContext.GetListBySql<Entity.Api.YPay>(sql, null).FirstOrDefault();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "获取Ypay数据");
                    return null;
                }
            }
        }
        /// <summary>
        /// 更新状态预支付
        /// </summary>
        /// <param name="Guid"></param>
        /// <param name="State"></param>
        /// <returns></returns>
        public bool UpdateYPay(string Guid, int State)
        {
            Entity.Api.YPay ypay = this.GetYPay(String.Format(" Guid='{0}'", Guid));

            if (ypay != null)
            {
                ypay.State = State;
                using (var dbContext = Repository.DbContext.Create())
                {
                    return dbContext.Update<Entity.Api.YPay>(ypay);
                }
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 费用查询
        /// <summary>
        /// 获取 费用查询
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="OrderFields"></param>
        /// <param name="isDesc"></param>
        /// <returns></returns>
        public Entity.Api.FeeQuery GetFeeQuery(string filter, string OrderFields = "", bool isDesc = false)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    string sql = "select * from FeeQuery";
                    if (filter.Length > 0)
                        sql += "  where  " + filter;
                    if (OrderFields.Length > 0)
                    {
                        if (isDesc)
                            sql += "   ORDER BY  " + OrderFields + "  DESC";
                        else
                            sql += "   ORDER BY  " + OrderFields;
                    }
                    return dbContext.GetListBySql<Entity.Api.FeeQuery>(sql, null).FirstOrDefault();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "获取FeeQuery数据");
                    return null;
                }
            }
        }
        public List<Entity.Api.FeeQuery> GetFeeQueryList(string filter, string OrderFields = "", bool isDesc = false)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    string sql = "select * from FeeQuery";
                    if (filter.Length > 0)
                        sql += "  where  " + filter;
                    if (OrderFields.Length > 0)
                    {
                        if (isDesc)
                            sql += "   ORDER BY  " + OrderFields + "  DESC";
                        else
                            sql += "   ORDER BY  " + OrderFields;
                    }
                    return dbContext.GetListBySql<Entity.Api.FeeQuery>(sql, null).ToList();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "获取FeeQuery数据");
                    return null;
                }
            }
        }
        /// <summary>
        /// 更新 费用查询状态
        /// </summary>
        /// <param name="Guid"></param>
        /// <param name="State"></param>
        /// <param name="Fee"></param>
        /// <returns></returns>
        public bool UpdateFeeQuery(string Guid, int State, int Fee = 0)
        {
            List<Entity.Api.FeeQuery> feeQuery = this.GetFeeQueryList(String.Format(" Guid='{0}'", Guid));

            if (feeQuery != null)
            {
                if (feeQuery.Count > 0)
                {
                    foreach (var item in feeQuery)
                    {
                        item.State = State;
                        if (Fee > 0)
                            item.Fee = Convert.ToDecimal((Fee / 100).ToString() + "." + ((Fee % 100).ToString().Length > 1 ? (Fee % 100).ToString() : "0" + (Fee % 100).ToString()));
                        using (var dbContext = Repository.DbContext.Create())
                        {
                            dbContext.Update<Entity.Api.FeeQuery>(item);
                        }
                    }
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 下发 费用查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddFeeQuery(Entity.Api.FeeQuery model)
        {
            Entity.Api.FeeQuery feeQuery = new Entity.Api.FeeQuery();
            feeQuery.Car_plate = model.Car_plate;
            feeQuery.Time = model.Time;
            feeQuery.Guid = model.Guid;
            feeQuery.DeviceClient_code = model.DeviceClient_code;
            feeQuery.EnterpriseID = model.EnterpriseID;
            feeQuery.EnterpriseName = model.EnterpriseName;
            feeQuery.CCEnterpriseID = model.CCEnterpriseID;
            feeQuery.CCEnterpriseName = model.CCEnterpriseName;
            feeQuery.Fee = 0.00m;
            feeQuery.State = 1;
            feeQuery.create_time = DateTime.Now;
            using (var dbContext = Repository.DbContext.Create())
            {
                return dbContext.Insert<Entity.Api.FeeQuery>(feeQuery);
            }
        }
        #endregion
        #region 月租费用查询
        /// <summary>
        /// 获取月租费用查询
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="OrderFields"></param>
        /// <param name="isDesc"></param>
        /// <returns></returns>
        public List<Entity.Api.MonthFeeQuery> GetMFeeQueryList(string filter, string OrderFields = "", bool isDesc = false)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    string sql = "select * from MonthFeeQuery";
                    if (filter.Length > 0)
                        sql += "  where  " + filter;
                    if (OrderFields.Length > 0)
                    {
                        if (isDesc)
                            sql += "   ORDER BY  " + OrderFields + "  DESC";
                        else
                            sql += "   ORDER BY  " + OrderFields;
                    }
                    return dbContext.GetListBySql<Entity.Api.MonthFeeQuery>(sql, null).ToList();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "获取FeeQuery数据");
                    return null;
                }
            }
        }
        /// <summary>
        /// 更新 月租费用查询状态
        /// </summary>
        /// <param name="Guid"></param>
        /// <param name="State"></param>
        /// <param name="Fee"></param>
        /// <returns></returns>
        public bool UpdateMFeeQuery(string Guid, int State, int Fee = 0)
        {
            List<Entity.Api.MonthFeeQuery> feeQuery = this.GetMFeeQueryList(String.Format(" Guid='{0}'", Guid));

            if (feeQuery != null)
            {
                if (feeQuery.Count > 0)
                {
                    foreach (var item in feeQuery)
                    {
                        item.State = State;
                        if (Fee > 0)
                            item.Fee = Convert.ToDecimal((Fee / 100).ToString() + "." + ((Fee % 100).ToString().Length > 1 ? (Fee % 100).ToString() : "0" + (Fee % 100).ToString()));
                        using (var dbContext = Repository.DbContext.Create())
                        {
                            dbContext.Update<Entity.Api.MonthFeeQuery>(item);
                        }
                    }
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 下发 月租费用查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddMFeeQuery(Entity.Api.MonthFeeQuery model)
        {
            Entity.Api.MonthFeeQuery feeQuery = new Entity.Api.MonthFeeQuery();
            feeQuery.Car_plate = model.Car_plate;
            feeQuery.Num = model.Num;
            feeQuery.Guid = model.Guid;
            feeQuery.DeviceClient_code = model.DeviceClient_code;
            feeQuery.EnterpriseID = model.EnterpriseID;
            feeQuery.EnterpriseName = model.EnterpriseName;
            feeQuery.CCEnterpriseID = model.CCEnterpriseID;
            feeQuery.CCEnterpriseName = model.CCEnterpriseName;
            feeQuery.Fee = 0.00m;
            feeQuery.State = 1;
            feeQuery.create_time = DateTime.Now;
            using (var dbContext = Repository.DbContext.Create())
            {
                return dbContext.Insert<Entity.Api.MonthFeeQuery>(feeQuery);
            }
        }
        #endregion
        /// <summary>
        /// 发送微信通知：进场通知
        /// </summary>
        /// <param name="order"></param>
        private void SendNotifyMsg(Entity.CarRecord car)
        {
            try
            {
                using (var dbContext = Repository.DbContext.Create())
                {
                    string sql = String.Format("SELECT us.[id],[openid],[nickname],[sex],[city],[province],[country],[headimgurl],[create_user],[update_user],[create_time],[update_time],[version] FROM [dbo].[wx_user] us INNER JOIN dbo.Car_Plate car ON us.id=car.Wx_userId WHERE car.Car_plate='{0}'", car.carBrand);
                    var userInfo = dbContext.GetListBySql<Entity.Wx_user>(sql, null).FirstOrDefault();
                    if (userInfo != null)
                    {

                        var msg = new Entity.DBGen.WXNotifyMsg()
                        {
                            MsgType = "WxCarIn",
                            Wx_userID = userInfo.id,
                            OpenId = userInfo.openid,
                            SendState = (byte)MsgSendState.Waiting,
                            LeaveTry = 0x01,
                            Content = Util.Conv.ToJson(new
                            {
                                first = "您好,您的车辆已经进入停车场。",
                                keyword1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                keyword2 = car.carBrand,
                                keyword3 = car.Enterprise_Name,
                                remark = "车辆离场时请提前缴费！"
                            }),
                            CreateTime = DateTime.Now,
                            CreateUser = "SERVER",
                        };
                        dbContext.Insert(msg);
                    }
                    else
                    {
                        LogHelper.Equals("用户未绑定车牌：" + car.carBrand, "微信推送消息写入");
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "微信推送消息写入");
            }
        }

        public void feeQuer()
        {
            string sql = "update FeeQuery set State=3 ,Fee=1.00";
            using (var dbContext = Repository.DbContext.Create())
            {
                dbContext.Execute(sql, null, System.Data.CommandType.Text);
            }
        }

    }
}
